// pages/gift_detail/gift_detail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [
      '../image/product_detail/pro1.png',
      '../image/product_detail/pro1.png',
      '../image/product_detail/pro1.png'
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    duihuan_success: false,
    zhe: false,
    fenxiang:false,
    R_code: '',
    jizanfou: false,
    product_id: ''
  },
  hide_model: function (e) {
    this.setData({
      duihuan_success: false,
      zhe: false
    })
  },
  // 兑换按钮
  dui: function () {
    var that = this;
    console.log(app.globalData.opid)
    console.log(that.data.detail.goods_id)
    console.log(that.data.detail.exchange_integral)
    wx.showModal({
      title: '提示',
      content: '确定兑换吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: app.globalData.url + 'ziyu.php?Action=duihuanliping',
            data: {
              openid: app.globalData.opid,
              R_productid: that.data.detail.goods_id,
              R_amount: that.data.detail.exchange_integral
            },
            success: function (res) {
              console.log(res)
              if (res.data.success == 0) {
                wx.showToast({
                  title: '账户余额不足',
                  icon: 'none'
                })
              } else {
                that.setData({
                  R_code: res.data.R_code,
                  duihuan_success: true,
                  zhe: true
                })
              }

            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },
 

  // 倒计时函数
  time_out() {
    var that = this;
    console.log(that.data.daojishi, (Date.parse(new Date()) / 1000))
    if (that.data.daojishi<0){
      clearInterval(that.data.intervarID);
     
      wx.request({
        url: app.globalData.url + 'collection.php?Action=chaoshishibai',
        data: {
          D_rid: that.data.d_id,
        },
        success: function (res) {
          console.log("chaoshishibai")
          
          if(that.data.clock != "已过期"){
            that.get_info()
            that.setData({
              clock: "已过期"
            })
          }else{
            
          }
        }
      })
     
      return false
    }
    var clear_dao = setInterval(function () {
       //计算剩余的毫秒数
      var leftTime = that.data.daojishi
      if (that.data.daojishi <= 0) {
        clearInterval(clear_dao);
        that.setData({
          clock: "已过期",
          daojishi:0
        })
        wx.request({
          url: app.globalData.url + 'collection.php?Action=chaoshishibai',
          data: {
            D_rid: that.data.d_id,
          },
          success: function (res) {
            console.log("chaoshishibai")
            if (that.data.clock != "已过期") {
              that.get_info()
             
            } else {

            }
          }
        })

      }else{
        leftTime = that.data.daojishi - 1;
      }
     
      that.setData({
        daojishi:leftTime
      })
      var days = parseInt(leftTime / 60 / 60 / 24, 10); //计算剩余的天数 
      var hours = parseInt(leftTime / 60 / 60 % 24, 10); //计算剩余的小时 
      var minutes = parseInt(leftTime / 60 % 60, 10);//计算剩余的分钟 
      var seconds = parseInt(leftTime % 60, 10);//计算剩余的秒数 
    //  输出倒计时时间
      that.setData({
        clock: days + "天" + hours + "小时" + minutes + "分" + seconds + "秒"
      })
      if (days <= '0' && hours <= '0' && minutes <= '0' && seconds <= '0') {
        
      }
    }, 1000)
  },
  shengcheng: function () {
    var that = this;
    if (app.globalData.userInfo == "") {
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function (res) {
                //从数据库获取用户信息
                console.log(res)
                app.globalData.userInfo = res.userInfo;
                that.setData({
                  user: res.userInfo
                })

              }
            });
          } else {
            wx.navigateTo({
              url: '../login/login?d_id=' + that.data.d_id + '&product_id=' + that.data.product_id
            })
          }
        }
      })
      return false
    }
    
    if (app.globalData.opid == "") {
      wx.navigateTo({
        url: '../login/login?d_id=' + that.data.d_id + '&product_id=' + that.data.product_id
      })
      return false
    } else {
    }


    wx.showLoading({
      title: '海报生成中...',
    })
    that.setData({
      zhe: true,
      fenxiang: true

    })

    wx.request({
      url: app.globalData.url + 'collection.php?Action=tuiguangerweima',
      data: {
        product_id: that.data.product_id,
        d_id: that.data.d_id,
        share_opid: app.globalData.shareopenid
      },
      success: function (res) {
        console.log(res)

        wx.downloadFile({
          url: res.data.erweima,
          success: function (res) {
            console.log(res.tempFilePath);
            var width = that.data.canvasWidth;
            var rem = width / 750;
            console.log(width)
            console.log(rem)
            var context = wx.createCanvasContext('myCanvas');
            context.setFillStyle("#fff");
            context.fillRect(0, 0, 700 * rem, 1250 * rem);



            var path = "./img/share.png";
            // 将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
            // 不知道是什么原因，手机环境能正常显示t
            context.drawImage(path, 0, 0, 700 * rem, 1250 * rem);
            console.log(that.data.user.nickName)
            context.setFontSize(48 * rem)
            context.setFillStyle("#fff");
            context.setTextAlign('center')
            context.fillText(that.data.user.nickName, 350 * rem, 330 * rem);



            // var name1 = "我已投票，支持" + that.data.detail.option_name;
            // console.log(name1)
            context.setFontSize(32 * rem)
            context.setFillStyle("#535353");
            context.setTextAlign('center')
            context.fillText("微信识别二维码，跟我一起集赞领礼品吧！", 350 * rem, 905 * rem);


            // context.setFontSize(32 * rem)
            // context.setFillStyle("#333333");
            // context.setTextAlign('left')
            // context.fillText("参赛宣言：", 40 * rem, 670 * rem);


            // var name3 = that.data.detail.option_content;

            // context.setFontSize(28 * rem)
            // context.setFillStyle("#666");
            // context.setTextAlign('left')
            // // context.fillText(name3, 40*rem, 720*rem);
            // that.drawText(context, name3, 40 * rem, 720 * rem, 148, (480 * rem))



            // context.setFontSize(36 * rem)
            // context.setFillStyle("#161616");
            // context.setTextAlign('left')
            // context.fillText("微信长按识别二维码", 360 * rem, 900 * rem);
            // context.fillText("为我助力吧", 360 * rem, 960 * rem);

            // context.setFillStyle("#fff");
            // context.setFontSize(40 * rem)
            // // context.font = 'normal bold sans-serif';
            // context.setTextAlign('center')
            // context.fillText(name, 350 * rem, 470 * rem);


            var path1 = res.tempFilePath;
            console.log(path1)
            context.drawImage(path1, 215 * rem, 550 * rem, 270 * rem, 270 * rem);



            wx.downloadFile({
              url: that.data.user.avatarUrl,
              success: res => {

                var avatarurl_width = 160 * rem;    //绘制的头像宽度
                var avatarurl_heigth = 160 * rem;   //绘制的头像高度
                var avatarurl_x = 270 * rem;   //绘制的头像在画布上的位置
                var avatarurl_y = 100 * rem;   //绘制的头像在画布上的位置
                context.save();
                context.beginPath(); //开始绘制
                context.setFillStyle("#fff");
                context.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, 85 * rem, 0, Math.PI * 2, false);

                context.clip();
                context.fill()
                context.restore();

                context.save();
                context.beginPath();
                //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
                context.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);

                context.clip();
                context.drawImage(res.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);

                context.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
                context.draw();
              }, fail: res => {
                console.log(res);
              }
            })




            setTimeout(function () {
              wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 700 * rem,
                height: 1250 * rem,
                destWidth: 700 * rem * 2,
                destHeight: 1250 * rem * 2,
                canvasId: 'myCanvas',
                success: function (res) {
                  console.log(res.tempFilePath)

                  var arr = [];
                  arr.push(res.tempFilePath)
                  wx.previewImage({
                    current: "", // 当前显示图片的http链接
                    urls: arr, // 需要预览的图片http链接列表
                    success: function (res) {
                      wx.hideLoading()
                      wx.request({
                        url: app.globalData.url + 'voting.php?Action=ffshare',
                        data: {
                          openid: app.globalData.opid,
                          S_types: 3,
                          S_productid: that.data.id
                        },
                        success: function (res) {
                          console.log(res)
                        }
                      })
                      that.setData({
                        zhe: false,
                        fenxiang: false

                      })
                    }
                  })

                },
                fail: function (res) {
                  console.log(res)
                  wx.hideLoading()
                  wx.showToast({
                    title: '海报生成失败，请重试',
                    icon: "none"
                  })
                }
              })
            }, 1000);

          }, fail: function (fres) {

          }
        })
      }
    })
  },
  // 帮他点赞
  help_good(e) {
    var that = this;
    console.log(app.globalData.opid, that.data.product_id, that.data.d_id, e.detail.formId)
    if (!app.globalData.opid == "") {
      wx.showLoading({
        title: '',
      })
      wx.request({
        url: app.globalData.url + 'collection.php?Action=bangtadianzan',
        data: {
          openid: app.globalData.opid,
          R_productid: that.data.product_id,
          D_rid: that.data.d_id,
          formid: (e.detail.formId == "the formId is a mock one"?"":e.detail.formId)
        },
        success: function (res) {
          console.log(res)
          wx.hideLoading()
          wx.showToast({
            title: res.data.msg,
            duration: 3000,
            mask: true,
            icon: 'none',
          })
          if (res.data.success == 1) {
            setTimeout(function () {
              that.get_info()
            }, 2000)
           
          }
        }
      })
    } else {
      wx.navigateTo({
        url: '../login/login?d_id='+that.data.d_id+'&product_id='+that.data.product_id,
      })
    }
   
  },
  // 我也要积攒
  go_jizan() {
   
    wx.switchTab({
      url: '../jizan_list/jizan_list',
    })
  },
  // 展开更多
  open_list() {
    var that = this;

    this.setData({
      friend_list: that.data.fi_list
    })
  },
  // 兑换礼品
  get_gift(e) {
    var that = this;
    wx.request({
      url: app.globalData.url + 'collection.php?Action=duihuan',
      data:{
        D_rid:that.data.d_id,
        formid: e.detail.formId,
        openid:app.globalData.opid
      },
      success:function(res){
        console.log(res)
        
          wx.showToast({
            title: res.data.msg,
            duration: 2000,
            mask: true,
            icon: 'none',
          })
        setTimeout(function () {
          that.get_info()
        }, 2000)
          
       
      }
    })
  },
  // 去集赞列表
  go_jizan_list(){
    var that = this;
    if (app.globalData.userInfo == "") {
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function (res) {
                //从数据库获取用户信息
                console.log(res)
                app.globalData.userInfo = res.userInfo;
                that.setData({
                  user: res.userInfo
                })

              }
            });
          } else {
            wx.navigateTo({
              url: '../login/login?d_id=' + that.data.d_id + '&product_id=' + that.data.product_id
            })
          }
        }
      })
      return false
    }
    wx.showLoading({
      title: '加载中',
    })
    if (app.globalData.opid == "") {
      wx.hideLoading()
      wx.navigateTo({
        url: '../login/login?d_id=' + that.data.d_id + '&product_id=' + that.data.product_id
      })
      return false
    }else{
      wx.hideLoading()
    }
    wx.navigateTo({
      url: '../my_jizan/my_jizan',
    })
  },
  // 复制验证码
  copy_code(e){
    console.log(e)
    wx.setClipboardData({
      data: e.currentTarget.dataset.code,
      success:function(res){
        wx.showToast({
          title: res.data,
          duration: 1000,
          mask: true,
          icon: 'none',
        })
      }
    })
  }, 
   // 获取商品信息
  get_info(){
    var that = this;
    wx.showLoading({
      title: '',
    })
    // 如果有d_id说明是从我的集赞列表来的
    if (that.data.d_id) {
      wx.request({
        url: app.globalData.url + 'collection.php?Action=jizandetail',
        data: {
          D_rid: that.data.d_id,
          R_productid: that.data.product_id
        },
        success: function (res) {
          console.log(res)
          wx.hideLoading()
          console.log('openid'+ res.data.R_openid)
          if (res.data.R_openid == app.globalData.opid) {
            that.setData({
              share_status: true
            })
          }
          that.setData({
            daojishi: res.data.daojishi,
            info: res.data
          })
         
           that.time_out()
         

        }
      })
      // 好友积攒列表
      wx.request({
        url: app.globalData.url + 'collection.php?Action=dianzanlist',
        data: {
          D_rid: that.data.d_id,
        },
        success: function (res) {
          console.log(res)
          // 如果数据大于4条，截前面4条输出
          if (res.data.length >= 4) {
            that.setData({
              fi_list: res.data,
              friend_list: res.data.slice(0, 4)
            })

          // 否则全部输出
          } else {
            that.setData({
              friend_list: res.data
            })
          }
          wx.hideLoading()
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log('积攒中心')
    console.log(options)

    // options={
    //   id :商品id
    //   d_id:集赞id
    //   share_openid：
    // }
    // 存储商品id跟集赞id
    if (options.share_opid){
      app.globalData.shareopenid = options.share_opid
    }

    console.log(app.globalData)
    this.setData({
      product_id: options.id,
      d_id: options.d_id
    })
    // 获取商品信息
    wx.request({
      url: app.globalData.url + 'exchange.php?&act=view',
      data: {
        id: options.id
      },
      success: function (res) {
        console.log(res)
        that.setData({
          detail: res.data
        })

      }
    })
    var myCanvasWidth;
    var myCanvasHeight;

    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        myCanvasWidth = res.windowWidth;
        myCanvasHeight = res.windowHeight;
      },
    })
    that.setData({
      canvasWidth: myCanvasWidth,
      canvasHeight: myCanvasHeight
    })
    // 如果有d_id说明是从我的集赞列表来的
    this.get_info()


    
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function (res) {
                //从数据库获取用户信息
                console.log(res)
                app.globalData.userInfo = res.userInfo;
                that.setData({
                  user: res.userInfo
                })

              }
            });
          }
        }
      })
    
    // 如果有share_id 说明从别人分享来的
    // if (options.share) {
    //   that.setData({
    //     share_status: true
    //   })
    // }

    // 图片
    wx.request({
      url: app.globalData.url + 'exchange.php?&act=pictures',
      data: {
        id: options.id
      },
      success: function (res) {
        console.log(res)
        that.setData({
          imgUrls: res.data,
          app_url: app.globalData.img_url
        })

      }
    })


    // 分享图片
    wx.request({
      url: app.globalData.url + 'ziyu.php?Action=danzhang&shuzi=10',
      success: function (res) {
        console.log(res)
        that.setData({
          share_img: res.data
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    console.log(app.globalData.userInfo)
    if (app.globalData.userInfo == "") {
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function (res) {
                //从数据库获取用户信息
                console.log(res)
                app.globalData.userInfo = res.userInfo;
                that.setData({
                  user: res.userInfo
                })

              }
            });
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    console.log(that.data.share_img)
    return {
      title: that.data.share_img[0].ad_link,
      path: '/pages/my_jizan_detail/my_jizan_detail?id=' + that.data.product_id + "&d_id=" + that.data.d_id + "&share_opid=" + app.globalData.opid ,
      imageUrl: that.data.share_img[0].ad_code
    }
  }
})